<template>
  <main class="px-6 pb-12">
    <div class="max-w-6xl mx-auto">
      <!-- 错误提示 -->
      <div v-if="errorMessage" class="mb-6 glass-card rounded-3xl p-6 bg-red-500/20 border border-red-500/30">
        <div class="flex items-center gap-3 text-red-200">
          <AlertCircle class="w-6 h-6" />
          <p>{{ errorMessage }}</p>
        </div>
      </div>

      <div class="glass-card rounded-3xl p-8">
        <div class="grid lg:grid-cols-2 gap-12">
          <!-- 左侧 - 速度仪表盘 -->
          <div class="flex flex-col items-center justify-center">
            <SpeedGauge
                :speed="currentInstantSpeed"
                :max-speed="1000"
                :is-active="isAnyTestRunning"
                :test-type="currentTestType"
            />

            <div class="mt-8 w-full max-w-sm">
              <TestButton
                  @start="startSpeedTest"
                  :is-running="isAnyTestRunning"
                  :progress="progress"
              />
            </div>
          </div>

          <!-- 右侧 - 测试结果 -->
          <div class="flex flex-col justify-center">
            <TestResults
                :download-speed="downloadSpeed"
                :upload-speed="uploadSpeed"
                :ping="ping"
                :jitter="jitter"
                :is-testing-download="isTestingDownload"
                :is-testing-upload="isTestingUpload"
                :is-testing-ping="isTestingPing"
                :results="testResults"
            />
          </div>
        </div>
      </div>
    </div>
  </main>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { AlertCircle } from 'lucide-vue-next'
import SpeedGauge from './SpeedGauge.vue'
import TestButton from './TestButton.vue'
import TestResults from './TestResults.vue'
import { useSpeedTest } from '../composables/useSpeedTest'

const {
  isTestingDownload,
  isTestingUpload,
  isTestingPing,
  downloadSpeed,
  uploadSpeed,
  ping,
  jitter,
  progress,
  errorMessage,
  startSpeedTest,
  testResults,

  /* 实时速度 */
  instantSpeed,
  instantUploadSpeed,
  instantPing
} = useSpeedTest()

const isAnyTestRunning = computed(
    () => isTestingDownload.value || isTestingUpload.value || isTestingPing.value
)

/* 🔥 仪表盘实时指针：谁活跃就显示谁的瞬时速度 */
const currentInstantSpeed = computed(() => {
  if (isTestingPing.value) return instantPing.value
  if (isTestingDownload.value) return instantSpeed.value
  if (isTestingUpload.value) return instantUploadSpeed.value
  return 0
})

const currentTestType = computed(() => {
  if (isTestingPing.value) return 'ping'
  if (isTestingDownload.value) return 'download'
  if (isTestingUpload.value) return 'upload'
  return 'idle'
})
</script>